package com.oedtech.esl.service.nettyService;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.*;

@Component
public class NettyServer {
    @Value("${ap.port}")
    private Integer port;
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyServer.class);

    @Autowired
    private AuthHandler authHandler;
    @Autowired
    private DataHandler dataHandler;
    public NettyServer() {
    }

//    public final static ExecutorService ex= Executors.newFixedThreadPool(5);//业务线程池，设置为cpu线程数的2倍
    public final static ExecutorService ex=new ThreadPoolExecutor(8,8,0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(30000),new ThreadPoolExecutor.DiscardPolicy());


    /**
     * 启动流程
     */
    public void run() throws InterruptedException {
        //配置服务端线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)

                    .channel(NioServerSocketChannel.class)
//                    .option(ChannelOption.SO_KEEPALIVE ,true)
                    .option(ChannelOption.SO_BACKLOG,1024)

                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,1,1))
                                    .addLast(new ReadTimeoutHandler(3))
                                    .addLast(authHandler)
                                    .addLast(dataHandler);
                        }
                    });

            LOGGER.info("netty服务器启动ing");

            //绑定端口，同步等待成功
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            //等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        }finally {

            //优雅退出，释放线程池
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

}
